<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

/* Restfull Routes */

// Product Routes
Route::get('/api/product/find/{id}', 'ProductController@getFind');
Route::get('/api/product/update/{id}', 'ProductController@getUpdate');
Route::post('/api/product/update', 'ProductController@postUpdate');
Route::post('/api/product/delete/{id}', 'ProductController@postDelete');
Route::post('/api/product/add', 'ProductController@postAdd');
Route::controller('api/product','ProductController');

// Category Routes
Route::get('/api/category/find/{id}', 'CategoryController@getFind');
Route::get('/api/category/update/{id}', 'CategoryController@getUpdate');
Route::post('/api/category/update', 'CategoryController@postUpdate');
Route::post('/api/product/delete/{id}', 'ProductController@postDelete');
Route::post('/api/product/add', 'ProductController@postAdd');
Route::controller('/api/category', 'CategoryController');

/* End of Restfull Routes */

Route::get('/product/stats', function() {

	return View::make('product.stats');
});

Route::get('login', function() {
	
	/* $user = Users::find(3);
	$user->password = Hash::make($user->password);
	$user->save(); */
	
	return View::make('users.login');
});

Route::get('register', function() {

	return View::make('users.register');
});

Route::post('register', function() {

	$person = new Person;
	$person->firstName = Input::get('firstname');
	$person->lastName = Input::get('lastname');
	$person->phoneNumber = Input::get('phonenumber');
	$person->workNumber = Input::get('worknumber');
	$person->primaryAddress = Input::get('address1');
	$person->secondaryAddress = Input::get('address2');

	$person->push();

	$payment = new Payment;
	$payment->paymentType  = Input::get('billingtype');
	$payment->cardNumber = Input::get('cardnumber');
	$payment->cvv = Input::get('cvv');
	$payment->expireDate = Input::get('expiredate');
	$payment->balance = 5000;

	$payment->save();

	$pass = Input::get('password');
	
	$user = new Users;
	$user->userName = Input::get('username');
	$user->password = Hash::make($pass);
	$user->Person_id = $person->id;
	$user->Payment_id = $payment->id;
	$user->Role_id = 1;

	$user->save();

	return Redirect::to('login');
});

Route::post('login', function() {

		$username = Input::get('username');
		$password = Input::get('password');

		if(Auth::attempt(array("userName" => $username, "password" => $password)))
		{
			$user = Users::where('userName', '=', $username)->First();
			$roleName = Role::where('id', '=', $user->Role_id)->pluck('roleName');
			
			if($roleName == "admin")
			{
				Session::put('isAdmin', 'true');
			}
			
			return Redirect::to('/');
		}
		else
		{
			$message = "Your username and password was incorrect";

			return Redirect::to('login') -> with('errors', $message);
		}
});

Route::get('logout', function() {

	Auth::logout();
	Session::flush();

	return Redirect::to('login');
});

Route::get('/product/view/{id}', function($id) {

	$item = Product::find($id);

	return View::make('product.index')
		-> with('item', $item);
});

Route::get('/cart/add/{id}', array("before" => "auth", function($id) {

	$found = false;
	$product = Product::find($id);

	$session = Session::get('cart');

	if(empty($session))
	{
		$cart = array();
		$cart[] = array("id" => $product->id, "name" => $product->productName, "price" => $product->retailPrice, "quantity" => 1, "thumbnail" => $product->image_url);

		Session::put('cart', $cart);
	}
	else
	{
		$cart = Session::get('cart');

		for($i = 0; $i < count($cart); $i++)
			# code...
		{
			if($cart[$i]['id'] === $product->id)
			{
				// The item was found in the cart already, increment the quantity
				$found = true;

				$cart[$i]['quantity']++;
				Session::put('cart', $cart);
				break;
			}
		}

		if($found == false)
		{
			$cart[] = array("id" => $product->id, "name" => $product->productName, "price" => $product->retailPrice, "quantity" => 1, "thumbnail" => $product->image_url);
			Session::put('cart', $cart);
		}		
	}

	$status = "Your item has been added to your cart.";
	//Session::put('add_status', $status);

	return Redirect::to('/')->with('status', $status);
}));

Route::get('/users/viewcart', array("before" => "auth", function() {

	$session_data = Session::get('cart');

	return View::make('users.cart')->with('cart', $session_data);
}));

Route::post('cart/destroy', array("before" => "auth", function() {

	/* This function will remove all the items in the users' shopping cart */

	Session::forget('cart');
	$message = "Your cart has been cleared";

	return Redirect::to('/')
		-> with("status", $message);
}));


Route::get('/users/checkout', array("before" => "auth", function() {

	$data = Session::get('cart');
	$total = 0;
	$id = Auth::user()->id;

	foreach ($data as $key => $value) {
			
			$product = Product::find($value['id']);

			if($product->quantity < $value['quantity'])
			{ 
				$status = "Sorry, you are trying to buy more items then what is available. There are currently only " .$product->quantity. " available.";
				return View::make('users.cart')
					-> with('status', $status)
					-> with('cart', Session::get('cart'));
			}
	}

	$balance = Payment::with('users')->find($id);

	foreach ($data as $item => $value) {
		
		$total += $value['price'] * $value['quantity'];
	}

	if($balance->balance < $total)
	{
		$error = "You have insuffecient balance to complete your transaction";

		return View::make('users.checkout')->with('error', $error);
	}


	return View::make('users.checkout') -> with('total', $balance->balance);
}));

Route::post('/users/purchase', function() {

	// Get all products the user wants to buy
	$products = Session::get('cart');

	//Create a new shopping cart object
	$cart = new ShoppingCart;
	$cart->users_id = Auth::user()->id;
	$cart->save();

	$date = date('Y-m-d H:i:s');

	// Assigning the shopping cart to the user


	$total = 0;

	foreach ($products as $item => $value) {
		# code...

		// Creating a new orderitem object
		$orderitem = new OrderItem;

		$temp = Product::find($value['id']);
		$temp->quantity -= $value['quantity'];

		$orderitem->quantity = $value['quantity'];
		$orderitem->tran_date = $date;
		$orderitem->Product_id = $value['id'];
		$orderitem->ShoppingCart_id = $cart->id;

		$orderitem->push();


		$total += $value['price'] * $value['quantity'];

	}

	// Update user balance
	$payment = Users::with('payment')->find(Auth::user()->id)->payment;
	$payment->balance -= $total;
	$payment->push();

	Session::forget('cart');
	Session::put('itemCount', 0);

	$status = "Your order was completed successfully";
	Session::put('complete_status', $status);

	return View::make('users.confirm') -> with('status', $status);

	// Write to the invoice table 
});

Route::get('product/category/{id}', function($id) {

	$categoryName = Category::find($id)->categoryName;
	
	$category = DB::table('Product')
            -> join('Category', 'Category.id', '=', 'Product.Category_id')  
			-> where('Category.id', '=', $id)            
            -> select('Product.id','Product.productName', 'Product.image_url')->get();

	return View::make('product.category')
		-> with('category', $categoryName)
		-> with('list', $category);
});

/* Admin routes */

Route::get('/users/profile/{usrnm}', function($usrnm){
	
	$usersId = DB::table('users')->where('userName', $usrnm)->pluck('id');
	$orders = DB::table('ShoppingCart')
            ->join('OrderItem', 'ShoppingCart.id', '=', 'OrderItem.shoppingcart_id') 
			->join('Product', 'OrderItem.product_id', '=', 'Product.id')             
            ->where('ShoppingCart.users_id', '=',$usersId)
            ->select('ShoppingCart.id','OrderItem.quantity','productName','retailPrice','tran_date')->get();
	
	return View::make('/users/profile')-> with('list', $orders)-> with('name1', $usrnm);
});

Route::get('Admin', function() {

	return View::make('Admin.Admin');
});

Route::get('Admin/Add', function() {

	$suppliers = Supplier::all();
	$categories = Category::all();

	return View::make('Product.add')
		-> with('suppliers', $suppliers)
		-> with('categories', $categories);
});

Route::get('Admin/Update', function() {

	$products = Product::all();

	return View::make('product.update')
		-> with('products', $products);
});

Route::get('Admin/Delete', function() {

	$products = Product::all();

	return View::make('product.delete')
		-> with('products', $products);
});

Route::get('Admin/Stats/Lowstock', function() {

	return View::make('Admin.stats');
});

Route::get('Admin/Stats/Stock', function() {

	$data = DB::table('product')
					-> whereBetween('quantity', array(1, 10))
					-> orderBy('quantity', 'asc')
					->take(5)->get();

	return Response::json($data);	
});

/* Additional Routes */

Route::get('/product/remove/{id}', function($id){
	
	$data = Session::get('cart');
	$count = 0;
	
	foreach ($data as $key => $value) {
		
		if($value['id'] == $id)
		{
			unset($data[$count]);
		}	
		
		$count++;
	}
	
	$data = array_values($data);
	
	Session::forget('cart');
	Session::put('cart', $data);
	
	return View::make('users.cart')
		-> with('cart', $data);
});

Route::get('product/increment/{id}', function($id) {
	
	$cart = Session::get('cart');
	$count = 0;
	
	foreach ($cart as $item => $value) {
		
		if($value['id'] == $id)
		{
			$cart[$count]['quantity']++;
		}
		
		$count++;
	}
	
	Session::put('cart', $cart);
	
	return View::make('users.cart')
		-> with('cart', $cart);
});

Route::get('product/decrement/{id}', function($id) {
	
	$cart = Session::get('cart');
	$count = 0;
	
	foreach ($cart as $item => $value) {
		
		if($value['id'] == $id)
		{
			if($cart[$count]['quantity'] > 1)
			{
				$cart[$count]['quantity']--;
			}		
			else {
				unset($cart[$count]);
			}
		}
		
		$count++;
	}
	
	$cart = array_values($cart);
	Session::put('cart', $cart);
	
	return View::make('users.cart')
		-> with('cart', $cart);
});

Route::get('/', array("before" => "auth", function()
{
	$data = Product::all();

	$cart = Session::get('cart');
	$itemCount = 0;

	if(!empty($cart))
	{
		$itemCount = count($cart);
	} 

	Session::put('itemCount', $itemCount);

	return View::make('hello') -> with('list', $data) -> with('itemCount', $itemCount);
}));



/* End of additional Routes */

/* Mapping RESTFul URL's */



/* Route::post('/rest/product/Add', 'ProductController@postAdd');
Route::get('/rest/product/Update/{id}', 'ProductController@getUpdate');
Route::post('/rest/product/Update/{id}', 'ProductController@postUpdate');
Route::post('/rest/product/Delete/{id}', 'ProductController@postDelete'); */


/* Defining RESTFul controllers */


